use std::collections::HashMap;
use std::io::{Error, Read, Write};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::tcp::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio::sync::broadcast::Sender;
use tokio::sync::Mutex;
use crate::message::{Message, MessageType};
use crate::my_error::MyError;

pub async fn send_data(writer: &mut WriteHalf<'_>, message: Message) -> Result<(), Box<dyn std::error::Error>> {
    let data = serde_json::to_string(&message)?;
    let mut data = data.as_bytes().to_vec();
    let data_len = data.len() as i64;
    let mut data_len_bytes = data_len.to_be_bytes();
    let mut data_len_bytes = data_len_bytes.to_vec();
    data_len_bytes.append(&mut data);
    writer.write_all(&data_len_bytes).await?;
    writer.flush().await?;
    Ok(())
}
pub async fn read_message(reader: &mut ReadHalf<'_>) -> Result<Message, MyError> {
    let mut data_len_bytes = [0; 8];
    match reader.read_exact(&mut data_len_bytes).await{
        Ok(n) => {
            if n == 0{
                log::debug!("Reading message none data from stream");
                return Err(MyError::ReadStreamNoneError);
            }
        },
        Err(e) => return Err(MyError::ReadStreamError(e))
    }
    let data_len = i64::from_be_bytes(data_len_bytes);
    let mut data = vec![0; data_len as usize];
    match reader.read_exact(&mut data).await{
        Ok(n) => {
            if n == 0 {
                log::debug!("Reading message none data from stream");
                return Err(MyError::ReadStreamNoneError);
            }
            // let data_str = String::from_utf8(data).unwrap();
            // let message: Message = serde_json::from_str(&data_str)?;
            let message: Message = serde_json::from_slice::<Message>(&data)?;
            log::debug!("Received message: {:?}", message);
            Ok(message)
        },
        Err(e) => Err(MyError::ReadStreamError(e))
    }

}